<template>
  <div class="resource-main-box new-page">
    <div class="pp-t-96">
      <h3 class="fw-b fs-14">分组管理</h3>
      <!-- 筛选条件与查询 -->
      <a-form-model layout="inline" :model="search">
        <a-form-model-item label="">
          <a-input
            v-model="search.groupName"
            style="width: 321px"
            placeholder="分组名称"
          >
            <a-icon slot="suffix" :component="require('@/assets/icon/search.svg')" @click="changeTable({current:1})" />
          </a-input>
        </a-form-model-item>

        <a-form-model-item>
          <a-button type="primary" ghost :loading="repReportParamGroupListLoading" @click="resetSearchHandler">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="pp-rb-box">
      <div class="d-flex" style="backgroundColor: #fff">
        <div class="ata-tree-box d-flex flex-column">
          <div class="tree-box-content" style="width:224px">
            <div>
              <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onNodeChange" />
              <a-tree
                :expanded-keys="expandedKeys"
                :auto-expand-parent="autoExpandParent"
                :tree-data="nodeList"
                :replace-fields="replaceFields"
                :checkable="true"
                @expand="onExpand"
                @check="onSelect"
              >
                <template slot="title" slot-scope="{ name }">
                  <span v-if="name.indexOf(searchValue) > -1">
                    {{ name.substr(0, name.indexOf(searchValue)) }}
                    <span style="color: #f50">{{ searchValue }}</span>
                    {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                  </span>
                  <span v-else>{{ name }}</span>
                </template>
              </a-tree>
            </div>
          </div>

        </div>
        <div class="ata-table-box flex-1 ml-24">
          <a-button type="primary" ghost :loading="repReportParamGroupListLoading" @click="addVisible=true">
            新增
          </a-button>
          <a-table
            :columns="columns"
            size="middle"
            class="mt-24"
            :data-source="repReportParamGroupList"
            :row-key="(row,index) => row.id"
            :pagination="{
              showTotal:(total)=> `共 ${total} 条数据`,
              showSizeChanger: true,//设置每页显示数据条数
              showQuickJumper: true,
              size:'big',
              current:paginationOptions.pageNum,
              pageSize:paginationOptions.pageSize,
              total:paginationOptions.total
            }"
            :loading="repReportParamGroupListLoading"
            :row-class-name="rowClassHandler"
            @change="changeTable"
          />
        </div>
      </div>
    </div>
    <!-- table -->

    <!-- <div class="pp-rb-box">
        <a-button type="primary" ghost :loading="repReportParamGroupListLoading" @click="addVisible=true">
          新增
        </a-button>

      <a-table
        :columns="columns"
        size="middle"
        :data-source="repReportParamGroupList"
        :row-key="(row,index) => row.id"
        :pagination="{
        showTotal:(total)=> `共 ${total} 条数据`,
          showSizeChanger: true,//设置每页显示数据条数
          showQuickJumper: true,
          size:'big',
          current:paginationOptions.pageNum,
          pageSize:paginationOptions.pageSize,
          total:paginationOptions.total
        }"
        :loading="repReportParamGroupListLoading"
        :row-class-name="rowClassHandler"
        @change="changeTable"
      />

    </div> -->

    <!-- add -->
    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :confirm-loading="addReportParamGroupListLoading"
      @ok="addConfirmHandler"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">{{ addTitle }}分组</div>
      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >

        <a-form-model-item label="分组名称" prop="name">
          <a-input v-model="addForm.name" placeholder="分组名称" style="width: 100%" class="input-type-o" />
        </a-form-model-item>
        <a-form-model-item label="一级分类" prop="smi">
          <a-select
            v-model="addForm.smi"
            style="minWidth: 130px"
            placeholder="一级分类"
            class="input-type-o"
            allow-clear
            @change="(v)=>getImiListHanlder(v,true)"
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in firstClassClassificationList" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item label="二级分类" prop="imi">
          <a-select
            v-model="addForm.imi"
            style="minWidth: 130px"
            placeholder="二级分类"
            class="input-type-o"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in secondaryClassificationListModel" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item prop="version">
          <span slot="label">版本号<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <a-input v-model="addForm.version" placeholder="版本号" style="width: 100%" class="input-type-o" />
        </a-form-model-item>
        <a-form-model-item prop="description">
          <span slot="label">分组描述<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <a-textarea
            v-model="addForm.description"
            style="width: 100%"
            class="input-type-o"
            :auto-size="{ minRows: 5, maxRows: 8 }"
          />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import rowClass from '@/pages/common/rowClass';
import getSmiAndModel from '../getSmiAndModel';
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex';
export default {
  mixins: [rowClass, getSmiAndModel],
  data() {
    return {
      search: {},
      addVisible: false,
      addForm: {},
      addTitle: '新增',
      addRules: Object.freeze({
        name: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        groupName: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        width: [
          { required: true, type: 'number', message: '请填写', trigger: 'change' }
        ],
        smi: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        imi: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        model: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      }),
      columns: Object.freeze([
        {
          title: '分组名称',
          dataIndex: 'name',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '描述',
          dataIndex: 'description',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '所属一级分类',
          dataIndex: 'smi',
          width: '140px',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '所属二级分类',
          dataIndex: 'imi',
          width: '140px',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 148,
          customRender: (value) => {
            return value ? this.$moment.utc(value) : '--';
          }
        },
        {
          title: '修改人',
          dataIndex: 'updateBy',
          width: 100,
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          width: 148,
          customRender: (value) => {
            return value ? this.$moment.utc(value) : '--';
          }
        },
        {
          title: '操作',
          dataIndex: 'option',
          width: 200,
          customRender: (value, record, index) => {
            const { id } = record;
            return [
              <a-button type='link' onClick={() => this.modifyHandler(record)}>修改</a-button>,
              <a-popconfirm
                title='确认删除此项?'
                ok-type='danger'
                ok-text='确认'
                cancel-text='取消'
                onConfirm={() => this.delItemHandler(id)}
              >

                <a-button type='link'>删除</a-button>
              </a-popconfirm>

              // <a-button type='primary' size='small' ghost>版本管理</a-button>
            ];
          }
        }
      ]),
      autoExpandParent: true, // node展开
      expandedKeys: [],
      searchValue: '',
      replaceFields: {
        children: 'childrenType',
        title: 'name'
      },
      nameList: [] // 选中node名称
    };
  },
  computed: {
    ...mapState('groupManagement', [
      'addReportParamGroupListLoading',
      'repReportParamGroupListLoading',
      'repReportParamGroupList',
      'paginationOptions',
      'repNodeParamGroupListLoading',
      'repNodeParamGroupList'
    ]),
    ...mapGetters('groupManagement', [
      'nodeList'
    ])
  },
  mounted() {
    // 获取一级分类
    this.getSmiList();
    this.changeTable({ current: 1 });
    this.getRepNodeParamGroupList();
  },

  methods: {
    ...mapActions('groupManagement', [
      'addRepReportParamGroup',
      'getRepReportParamGroupList',
      'modifyRepReportParamLabel',
      'getRepNodeParamGroupList',
      'removeRepReportParamGroup'
    ]),
    ...mapMutations('groupManagement', [
      'setState'
    ]),
    // 重置
    resetSearchHandler() {
      this.search = {};
      this.getData();
    },
    addConfirmHandler() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.addForm.id) {
            this.modifyRepReportParamLabel(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.getData();
              }
            });
          } else {
            this.addRepReportParamGroup(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.getData();
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    changeTable({ current, pageSize = 10 }, params = {}) {
      if (pageSize !== this.paginationOptions.pageSize) {
        current = 1;
      }
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getData();
    },
    cancelHandler() {
      this.addForm = {};
      this.addTitle = '新增';
      this.$refs.addForm.resetFields();
    },
    // 修改预赋值
    modifyHandler(row) {
      this.addVisible = true;
      this.addForm = { ...row };
      this.addTitle = '修改';
    },
    // 确认删除
    delItemHandler(id) {
      this.removeRepReportParamGroup({ id }).then((rep) => {
        if (rep) {
          this.getData();
        }
      });
    },
    // 获取table
    getData() {
      const params = { ...this.search };
      params.name = this.nameList;
      this.getRepReportParamGroupList(params);
    },
    // 输入node
    onNodeChange(e) {
      let value = e.target.value;
      if (!value) {
        this.expandedKeys = [];
        this.searchValue = '';
        return;
      }
      value = value.toUpperCase();
      const expandedKeys = this.nodeList
        .map(item => {
          if (item.name.indexOf(value) > -1) {
            return item.key;
          } else {
            return this.getParentKey(value, item);
          }
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      });
    },
    getParentKey(value, tree) {
      let parentKey;
      const list = tree.childrenType;
      for (let i = 0; i < list.length; i++) {
        const node = list[i];
        if (node.name.indexOf(value) > -1) {
          parentKey = tree.key;
        }
      }
      return parentKey;
    },
    // Node列表展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    // 选中Node节点
    onSelect(k, { checkedNodes }) {
      this.nameList = checkedNodes.map(item => {
        return item.data.props.name;
      });
      this.getData();
    }
  }
};
</script>

<style lang="less">
@import 'index.less';
</style>
